﻿using System;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;

namespace Hxsoft.Web.Util
{
	public class Net
	{
		/// <summary>
		/// 获取 url 的 Html 数据。
		/// </summary>
		/// <param name="url">获取的 url。</param>
		/// <returns>url 的 Html 数据。</returns>
		public static string GetHttpData(string url)
		{
			return GetHttpData(url, null);
		}

		/// <summary>
		/// 获取 url 的 Html 数据。
		/// </summary>
		/// <param name="url">获取的 url。</param>
		/// <param name="encodeName">编码名称。</param>
		/// <returns>url 的 Html 数据。</returns>
		public static string GetHttpData(string url, string encodeName)
		{
			string sRslt = null;
			WebResponse oWebRps = null;
			WebRequest oWebRqst = WebRequest.Create(url);
			oWebRqst.Timeout = 50000;
			try
			{
				oWebRps = oWebRqst.GetResponse();
			}
			finally
			{
				if (oWebRps != null)
				{
					if (string.IsNullOrEmpty(encodeName)) encodeName = GetWebResponseContentEncodeName(oWebRps);
					StreamReader oStreamRd = new StreamReader(oWebRps.GetResponseStream(), string.IsNullOrEmpty(encodeName) ? Encoding.Default : Encoding.GetEncoding(encodeName));
					sRslt = oStreamRd.ReadToEnd();
					oStreamRd.Close();
					oWebRps.Close();
				}
			}
			return sRslt;
		}

		/// <summary>
		/// 获取 Response 内容编码类型。
		/// </summary>
		/// <param name="response">WebResponse 对象。</param>
		/// <returns>内容编码类型。</returns>
		public static string GetWebResponseContentEncodeName(WebResponse webResponse)
		{
			Regex reg_charset = new Regex(@"charset\b\s*=\s*(?<charset>[^""]*)");
			WebHeaderCollection headers = webResponse.Headers;

			string encodingName = null;
			string contentType = headers["Content-Type"];
			if (contentType.IndexOf("charset") > 0 && reg_charset.IsMatch(contentType))
			{
				encodingName = reg_charset.Match(contentType).Groups["charset"].Value;
			}
			return encodingName;
		}
	}
}
